// pages/food/add.js
const { post, put, get, upload } = require('../../utils/request');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        form: {
            name: '',
            category: '',
            unit: '',
            calories: '',
            protein: '',
            carbs: '',
            fat: '',
            fiber: '',
            sugar: '',
            sodium: '',
            image: ''
        },
        categoryIndex: null,
        unitIndex: null,
        categories: [
            { value: 'staple', label: '主食' },
            { value: 'meat', label: '肉类' },
            { value: 'vegetable', label: '蔬菜' },
            { value: 'fruit', label: '水果' },
            { value: 'drink', label: '饮品' },
            { value: 'other', label: '其他' }
        ],
        units: ['100克', '100毫升', '个', '份', '勺'],
        isFormValid: false,
        isEdit: false,
        foodId: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.id) {
            this.setData({
                isEdit: true,
                foodId: options.id
            });
            this.loadFoodData(options.id);
            wx.setNavigationBarTitle({
                title: '编辑食物'
            });
        } else {
            wx.setNavigationBarTitle({
                title: '添加食物'
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 表单输入处理函数
    onNameInput(e) {
        this.setData({
            'form.name': e.detail.value
        });
        this.validateForm();
    },

    onCategoryChange(e) {
        const index = e.detail.value;
        this.setData({
            categoryIndex: index,
            'form.category': this.data.categories[index].value
        });
        this.validateForm();
    },

    onUnitChange(e) {
        const index = e.detail.value;
        this.setData({
            unitIndex: index,
            'form.unit': this.data.units[index]
        });
        this.validateForm();
    },

    onCaloriesInput(e) {
        this.setData({
            'form.calories': e.detail.value
        });
        this.validateForm();
    },

    onProteinInput(e) {
        this.setData({
            'form.protein': e.detail.value
        });
        this.validateForm();
    },

    onCarbsInput(e) {
        this.setData({
            'form.carbs': e.detail.value
        });
        this.validateForm();
    },

    onFatInput(e) {
        this.setData({
            'form.fat': e.detail.value
        });
        this.validateForm();
    },

    onSugarInput(e) {
        this.setData({
            'form.sugar': e.detail.value
        });
        this.validateForm();
    },

    onFiberInput(e) {
        this.setData({
            'form.fiber': e.detail.value
        });
        this.validateForm();
    },

    onSodiumInput(e) {
        this.setData({
            'form.sodium': e.detail.value
        });
        this.validateForm();
    },

    // 验证表单
    validateForm() {
        const { name, category, unit, calories, protein, carbs, fat } = this.data.form;
        const isValid = name && 
                       category && 
                       unit && 
                       calories && 
                       protein && 
                       carbs && 
                       fat;
        
        this.setData({
            isFormValid: isValid
        });
    },

    // 选择图片
    async chooseImage() {
        try {
            const res = await wx.chooseMedia({
                count: 1,
                mediaType: ['image'],
                sourceType: ['album', 'camera']
            });

            wx.showLoading({
                title: '上传中...',
            });

            const tempFilePath = res.tempFiles[0].tempFilePath;
            const uploadRes = await upload('/upload/image', tempFilePath, 'image');

            this.setData({
                'form.image': uploadRes.url
            });

            wx.hideLoading();
        } catch (error) {
            console.error('上传图片失败:', error);
            wx.hideLoading();
            wx.showToast({
                title: '上传失败',
                icon: 'none'
            });
        }
    },

    async loadFoodData(id) {
        try {
            wx.showLoading({
                title: '加载中...'
            });

            const res = await get(`/foods/${id}`);
            const food = res;

            // 设置分类索引
            const categoryIndex = this.data.categories.findIndex(
                item => item.value === food.category
            );

            // 设置单位索引
            const unitIndex = this.data.units.findIndex(
                unit => unit === food.unit
            );

            this.setData({
                form: {
                    name: food.name,
                    category: food.category,
                    unit: food.unit,
                    calories: food.calories.toString(),
                    protein: food.protein.toString(),
                    carbs: food.carbs.toString(),
                    fat: food.fat.toString(),
                    fiber: food.fiber ? food.fiber.toString() : '',
                    sugar: food.sugar ? food.sugar.toString() : '',
                    sodium: food.sodium ? food.sodium.toString() : '',
                    image: food.image || ''
                },
                categoryIndex: categoryIndex !== -1 ? categoryIndex : null,
                unitIndex: unitIndex !== -1 ? unitIndex : null
            });

            this.validateForm();
            wx.hideLoading();
        } catch (error) {
            console.error('加载食物数据失败:', error);
            wx.hideLoading();
            wx.showToast({
                title: '加载失败',
                icon: 'none'
            });
        }
    },

    // 提交表单
    async handleSubmit() {
        if (!this.data.isFormValid) return;

        try {
            wx.showLoading({
                title: '保存中...'
            });

            const formData = {
                ...this.data.form,
                calories: parseFloat(this.data.form.calories),
                protein: parseFloat(this.data.form.protein),
                carbs: parseFloat(this.data.form.carbs),
                fat: parseFloat(this.data.form.fat),
                fiber: this.data.form.fiber ? parseFloat(this.data.form.fiber) : 0,
                sugar: this.data.form.sugar ? parseFloat(this.data.form.sugar) : 0,
                sodium: this.data.form.sodium ? parseFloat(this.data.form.sodium) : 0
            };

            if (this.data.isEdit) {
                await put(`/foods/${this.data.foodId}`, formData);
                wx.showToast({
                    title: '更新成功',
                    icon: 'success'
                });
            } else {
                await post('/foods', formData);
                wx.showToast({
                    title: '添加成功',
                    icon: 'success'
                });
            }

            // 返回上一页并刷新数据
            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        } catch (error) {
            console.error(this.data.isEdit ? '更新食物失败:' : '添加食物失败:', error);
            wx.hideLoading();
            wx.showToast({
                title: error.message || (this.data.isEdit ? '更新失败' : '添加失败'),
                icon: 'none'
            });
        }
    }
})